package com.rupeng.web.resolver;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.rupeng.util.AjaxResult;
import com.rupeng.util.JsonUtils;

@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver{
	private static final Logger logger = LogManager.getLogger(MyHandlerExceptionResolver.class);
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		logger.error("服务器出错",ex);
		//考虑请求的类型
		if (request.getHeader("X-Requested-With")!=null) {
			//ajax请求
			AjaxResult ajaxResult = AjaxResult.errorInstance("服务器出错了");
			try {
				response.getWriter().print(JsonUtils.toJson(ajaxResult));
			} catch (IOException e) {
				logger.error("ajax错误信息写入异常",e);
			}
			return new ModelAndView();
		} else {
			return new ModelAndView("500");
		}
	}
}
